<?php

namespace App\Http\Controllers;

use App\Cate;
use Illuminate\Http\Request;

class CateController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $where = [];
        if(!empty($request->start)){
            $where[] = ['created_at',">",$request->start];
        }
        if(!empty($request->end)){
            $where[] = ['created_at',"<",$request->end];
        }
        if(!empty($request->name)){
            $where[] = ['name',$request->name];
        }
        $cates = Cate::where($where)->paginate(2);

        return view("admin.cate.index",compact("cates", "request"));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view("admin.cate.create");
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Cate $cates, Request $request)
    {
        $this->validate($request,[
           "name"=>"required|unique:cates|max:10|min:1",
        ],
        [
            "name.unique"=>"分类名称不能重复",
            "name.required"=>"分类名称必须填写",
            "name.max"=>"分类名称过长",
            "name.min"=>"分类名称过短",
        ]
        );
        $cates->name = $request->name;
        $cates->save();
        return back();
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit(Cate $cate)
    {
        //
        return view("admin.cate.edit", compact("cate"));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Cate $cate)
    {
        //
        $this->validate($request,[
            "name"=>"unique:cates,name,".$cate->id,
        ]);
        $cate->name = $request->name;
        $cate->save();
        return back();
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy(Cate $cate)
    {
        //
        $cate->delete();
        return back();
    }

    public function destroyAll(Request $request)
    {
        $res = Cate::destroy($request->data);
        if ($res){
            return [
                "error"=>0,
            ];
        }
    }
}
